package com.shanzmoo.admin.web;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.shanzmoo.admin.domain.ExeclExportSet;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * 基础controller
 * @author fs
 */
public class BaseController {
    public HttpServletResponse response(){
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletResponse response = ((ServletRequestAttributes)requestAttributes).getResponse();
        return response;
    }
    public void exportByBean(List<ExeclExportSet> set,List data,String title){
        try{
            HttpServletResponse response = response();
            // 通过工具类创建writer，默认创建xls格式
            ExcelWriter writer = ExcelUtil.getWriter();
            //自定义标题别名
            for(ExeclExportSet one:set){
                writer.addHeaderAlias(one.getField(), one.getName());
            }
            writer.setOnlyAlias(true);
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(data, true);
            //out为OutputStream，需要写出到的目标流
            //response为HttpServletResponse对象
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(title, "UTF-8")+".xls");
            ServletOutputStream out=response.getOutputStream();
            writer.flush(out, true);
            // 关闭writer，释放内存
            writer.close();
            //此处记得关闭输出Servlet流
            IoUtil.close(out);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

}
